﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceStack.Redis.Support;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace TKWeb
{
	public partial class Test : System.Web.UI.Page
	{
		private ObjectSerializer serializer = new ObjectSerializer();
		protected void Page_Load(object sender, EventArgs e)
		{
			string reqUrl = "http://movie.douban.com/subject/1929463/";
			string inCookie = null;
			string outCookie = null;
			string url = null;
			string str = null;
			str = GetWeb0("http://www.microsofttranslator.com/bv.aspx?from=lt&to=zh-chs&a=" + HttpUtility.UrlEncode(reqUrl), "utf-8", null, out outCookie);

			Regex regex = new Regex(@"BV.InitRoot\('http\\x3a\\x2f\\x2f(.+?)\\x2fbvsandbox.aspx',");
			Match m = regex.Match(str);
			if (m.Success)
			{
				inCookie = outCookie;
				string ip = m.Result("$1");
				string sign = null;
				url = string.Format("http://{0}/bvsandbox.aspx?&dl=zh-CHS&from=lt&to=zh-CHS&a={1}", ip, HttpUtility.UrlEncode(reqUrl));
				str = GetWeb0(url, "utf-8", inCookie, out outCookie);

				regex = new Regex(@"BV.Init\('http:\/\/www.microsofttranslator.com/', '(.+?)', '(.+?)'\);");
				m = regex.Match(str);
				if (m.Success)
				{
					ip = m.Result("$1");
					sign = m.Result("$2");

					inCookie = outCookie;
					url = string.Format("{0}proxy.ashx?h={1}&a={2}", ip, sign, HttpUtility.UrlEncode(reqUrl));
					str = GetWeb0(url, "utf-8", inCookie, out outCookie);
				}
			}
		}


		private string GetWeb0(string url, string encoding, string inCookie, out string outCookie)
		{
			outCookie = null;
			string html = null;
			HttpWebResponse response = null;
			StreamReader stream = null;
			try
			{
				HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
				webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1";
				webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
				webRequest.Referer = url;
				webRequest.Headers.Add("Cache-Control", "max-age=0");
				webRequest.Credentials = CredentialCache.DefaultCredentials;
				webRequest.KeepAlive = true;
				if (string.IsNullOrEmpty(inCookie))
				{
					webRequest.Headers.Add("Cookie", inCookie);
				}

				webRequest.ReadWriteTimeout = 30 * 1000;
				response = (HttpWebResponse)webRequest.GetResponse();
				if (response.StatusCode == HttpStatusCode.OK)
				{
					outCookie = response.Headers.Get("Set-Cookie");
					stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
					html = stream.ReadToEnd();
				}
			}
			catch (Exception ex)
			{
				return null;
			}
			finally
			{
				if (response != null)
					response.Close();

				if (stream != null)
					stream.Close();
			}
			return html;
		}


		private string GetWeb(string url, string encoding, string cookie)
		{
			string html = null;
			HttpWebResponse response = null;
			StreamReader stream = null;
			try
			{
				HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
				WebProxy proxy = WebProxy.GetDefaultProxy();
				proxy.Address = new Uri("http://" + Request["ip"]);
				proxy.Credentials = new NetworkCredential("username", "password");

				webRequest.Proxy = proxy;
				webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1";
				webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
				webRequest.Referer = url;
				webRequest.Headers.Add("Cache-Control", "max-age=0");
				webRequest.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
				webRequest.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
				webRequest.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
				webRequest.Credentials = CredentialCache.DefaultCredentials;
				webRequest.KeepAlive = true;
				if (string.IsNullOrEmpty(cookie))
				{
					webRequest.Headers.Add("Cookie", cookie);
				}

				webRequest.ReadWriteTimeout = 30 * 1000;
				response = (HttpWebResponse)webRequest.GetResponse();
				if (response.StatusCode == HttpStatusCode.OK)
				{
					stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
					html = stream.ReadToEnd();
				}
			}
			catch (Exception ex)
			{
				return null;
			}
			finally
			{
				if (response != null)
					response.Close();

				if (stream != null)
					stream.Close();
			}
			return html;
		}

		public void Add(int item)
		{
			using (var redisClent = Global.GetRedisClient())
			{
				redisClent.SAdd("set_test", serializer.Serialize(item));
			}
		}

		public bool IsMember(int item)
		{
			using (var redisClent = Global.GetRedisClient())
			{
				return redisClent.SIsMember("set_test", serializer.Serialize(item)) == 1;
			}
		}

		public void Remove(int item)
		{
			using (var redisClent = Global.GetRedisClient())
			{
				redisClent.RemoveItemFromSet("set_test", item.ToString());
			}
		}

		protected void Button1_Click(object sender, EventArgs e)
		{
			Regex regex = new Regex("<span class=\"youdao-hiddenspan\">.+?</span>");
			TextBox3.Text =  regex.Replace(TextBox2.Text, "");

			regex = new Regex(@"javascript:changelink\('(.+?)','SP2ZH_CN'\);");
			TextBox3.Text = regex.Replace(TextBox3.Text, "$1");
		}

		public string GetWeb2(string url)
		{
			using (WebClient wc = new WebClient())
			{
				url = string.Format("http://fanyi.youdao.com/WebpageTranslate?keyfrom=webfanyi.top&url={0}&type=SP2ZH_CN", System.Web.HttpUtility.UrlEncode(url));
				wc.Encoding = System.Text.Encoding.UTF8;
				string str = wc.DownloadString(url);

				Regex regex = new Regex("getElementById\\(\"youdaotranslateIframe\"\\)\\.src=\"(.+?)\";");
				url  = regex.Match(str).Result("$1");

				str = wc.DownloadString(url);
				wc.Encoding = System.Text.Encoding.UTF8;
				regex = new Regex("<span class=\"youdao-hiddenspan\">.+?</span>");
				str = regex.Replace(str, "");

				regex = new Regex(@"javascript:changelink\('(.+?)','SP2ZH_CN'\);");
				str = regex.Replace(str, "$1");
				Response.Write(str);
				return str;
			}
		}

		public string GetWeb3(string url)
		{
			using (WebClient wc = new WebClient())
			{
				url = string.Format("http://www.microsofttranslator.com/bv.aspx?from=lt&to=zh-chs&a={0}", System.Web.HttpUtility.UrlEncode(url));
				wc.Encoding = System.Text.Encoding.UTF8;
				string str = wc.DownloadString(url);

				Regex regex = new Regex("getElementById\\(\"youdaotranslateIframe\"\\)\\.src=\"(.+?)\";");
				url = regex.Match(str).Result("$1");

				str = wc.DownloadString(url);
				wc.Encoding = System.Text.Encoding.UTF8;
				regex = new Regex("<span class=\"youdao-hiddenspan\">.+?</span>");
				str = regex.Replace(str, "");

				regex = new Regex(@"javascript:changelink\('(.+?)','SP2ZH_CN'\);");
				str = regex.Replace(str, "$1");
				Response.Write(str);
				return str;
			}
		}

	}
}